package com.slmxz.tms.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slmxz.tms.biz.enums.OrderSpecialTypeEnum;
import com.slmxz.tms.biz.enums.OrderStatusEnum;
import com.slmxz.tms.biz.enums.TransportTypeEnum;
import com.slmxz.tms.biz.mapper.OrderLocationMapper;
import com.slmxz.tms.biz.mapper.OrderMapper;
import com.slmxz.tms.biz.model.entity.Order;
import com.slmxz.tms.biz.model.entity.OrderCargo;
import com.slmxz.tms.biz.model.entity.OrderLifecycle;
import com.slmxz.tms.biz.model.entity.OrderLocation;
import com.slmxz.tms.biz.model.vo.OrderVO;
import com.slmxz.tms.biz.service.OrderCargoService;
import com.slmxz.tms.biz.service.OrderLifecycleService;
import com.slmxz.tms.biz.service.OrderService;
import com.slmxz.tms.common.base.IBaseEnum;
import com.slmxz.tms.common.component.NoGeneratorService;
import com.slmxz.tms.common.component.PrimaryKeyGeneratorService;
import com.slmxz.tms.common.component.RedisUserService;
import com.slmxz.tms.common.constant.NumberContants;
import com.slmxz.tms.common.constant.SystemConstants;
import com.slmxz.tms.common.enums.BizMessageEnum;
import com.slmxz.tms.common.enums.TableEnum;
import com.slmxz.tms.core.exception.Asserts;
import com.slmxz.tms.core.exception.BizException;
import com.slmxz.tms.core.service.DataScopeService;
import com.slmxz.tms.core.service.PrimaryKeySerivce;
import com.slmxz.tms.document.mapper.LocationMapper;
import com.slmxz.tms.document.model.entity.Location;
import com.slmxz.tms.system.model.vo.UserInfoVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 订单服务实现类
 * @author sunyao
 * @Date 2024-12-01
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService, PrimaryKeySerivce<Order>, DataScopeService<OrderVO> {

    @Value("${orderNo.prefix}")
    private String orderNoPrefix;

    private final OrderLocationMapper orderLocationMapper;
    private final LocationMapper locationMapper;
    private final OrderLifecycleService orderLifecycleService;
    private final OrderCargoService orderCargoService;
    /**
    * 获取订单分页列表
    * @return {@link IPage< OrderVO >} 订单分页列表
    */
    @Override
    public IPage<OrderVO> selectOrderPage(IPage<OrderVO> page,OrderVO order) {
       UserInfoVO user = RedisUserService.currentUser();
       try{
           this.dataScopeHandler(order);
       }catch (Exception e){
           order.setScopeNo(user.getScopeNo());
           order.setDataOperate(SystemConstants.OPERATE_EQUALS);
       }
        order.setCompanyId(user.getCompanyId());
        List<OrderVO> orders = this.baseMapper.selectOrderPage(page,order);
        if(CollectionUtil.isNotEmpty(orders)){
            orders.forEach(orderItem -> {
                orderItem.setOrderStatusLabel(IBaseEnum.getLabelByValue(orderItem.getOrderStatus(), OrderStatusEnum.class));
                orderItem.setSpecialTypeLabel(IBaseEnum.getLabelByValue(orderItem.getSpecialType(), OrderSpecialTypeEnum.class));
                orderItem.setTransportTypeLabel(IBaseEnum.getLabelByValue(orderItem.getTransportType(), TransportTypeEnum.class));
            });
        }
        return page.setRecords(orders);
    }
    
    /**
     * @param id 订单ID
     * @return
     */
    @Override
    public OrderVO selectOrderDetail(Long id) {
        Asserts.fail(id == null,BizMessageEnum.PARAM_IS_NULL);

        Order entity = this.getById(id);
        Asserts.fail(entity == null,BizMessageEnum.BIZ0000001);

        OrderVO order = BeanUtil.copyProperties(entity,OrderVO.class);
        //获取订单地址数据
        OrderLocation orderLocation = this.orderLocationMapper.selectOne(new QueryWrapper<OrderLocation>()
                .lambda().eq(OrderLocation::getOrderNo,entity.getOrderNo()));
        BeanUtil.copyProperties(orderLocation,order);
        order.setId(entity.getId());
        //获取订单货物信息
        List<OrderCargo> orderCargos = this.orderCargoService.list(new QueryWrapper<OrderCargo>().lambda().eq(OrderCargo::getOrderNo,order.getOrderNo()));
        order.setOrderCargos(orderCargos);
        return order;
    }
    
    /**
     * 新增订单
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrder(OrderVO order) throws Exception {
        UserInfoVO user = RedisUserService.currentUser();
        //创建订单ID
        Long orderId = this.getId(); //创建订单表主键
        //复制成数据库订单实体
        Order orderParam = BeanUtil.copyProperties(order,Order.class);
        orderParam.setId(orderId);
        //设置订单所在公司和部门,数据隔离
        order.setCompanyId(user.getCompanyId());
        order.setDeptId(user.getDeptId());
        //生成订单号
        String orderNo = orderParam.getOrderNo();
        if(StrUtil.isBlank(orderNo)){
            orderNo = NoGeneratorService.generatorNo(this.orderNoPrefix,10000); //订单的尾号从10000开始,订单号的前缀则是公司的标识
            orderParam.setOrderNo(orderNo);
        }else{
            //校验业务人员自己录入的订单号是否存在，整个系统保持唯一
            this.validateOrderNo(orderNo);
        }
        orderParam.setOrderStatus(1); //正常
        orderParam.setSpecialType(1); //没有发生拆并得订单,也就是原单
        orderParam.setCompanyId(user.getCompanyId());
        orderParam.setDeptId(user.getDeptId());
        //复制订单中得地址属性
        OrderLocation orderLocation = BeanUtil.copyProperties(order,OrderLocation.class);
        if(order.getLoadingLocationId() != null){
            //校验起运地地址是否存在
            Location loadingLocation = this.locationMapper.selectById(order.getLoadingLocationId());
            Asserts.fail(loadingLocation == null,BizMessageEnum.LOADING_LOCATION_NOT_EXIST);

            orderLocation.setLoadingLocationName(loadingLocation.getLocationName());
            orderLocation.setLoadingProvince(loadingLocation.getProvince());
            orderLocation.setLoadingCity(loadingLocation.getCity());
            orderLocation.setLoadingDistrict(loadingLocation.getDistrict());
            orderLocation.setLoadingLongitude(loadingLocation.getLongitude());
            orderLocation.setLoadingLatitude(loadingLocation.getLatitude());
        }
        if(order.getDischargeLocationId()!= null){
            //校验目的地地址是否存在
            Location dischargeLocation = this.locationMapper.selectById(order.getDischargeLocationId());
            Asserts.fail(dischargeLocation == null,BizMessageEnum.DEST_LOCATION_NOT_EXIST);

            orderLocation.setDischargeLocationName(dischargeLocation.getLocationName());
            orderLocation.setDischargeProvince(dischargeLocation.getProvince());
            orderLocation.setDischargeCity(dischargeLocation.getCity());
            orderLocation.setDischargeDistrict(dischargeLocation.getDistrict());
            orderLocation.setDischargeLongitude(dischargeLocation.getLongitude());
            orderLocation.setDischargeLatitude(dischargeLocation.getLatitude());
        }
        Long orderLocationId = PrimaryKeyGeneratorService.generateId(TableEnum.TABLE_ORDER_LOCATION);
        //保存订单得地址数据
        orderLocation.setOrderNo(orderNo);
        orderLocation.setId(orderLocationId);
        orderLocation.setUpdateBy(user.getId());
        orderLocation.setUpdateTime(LocalDateTime.now());
        this.orderLocationMapper.insert(orderLocation);

        //更改订单货物数据
        List<OrderCargo> orderCargos = order.getOrderCargos();
        if(CollectionUtils.isEmpty(orderCargos)){
            throw new BizException("货物数据不能为空!");
        }
        //新增订单货物数据
        this.orderCargoService.adjustOrderCargo(orderCargos,orderNo);
        //统计修改后订单的件毛体
        int orderPcs = 0;
        BigDecimal orderWeight = BigDecimal.ZERO;
        BigDecimal orderVolume = BigDecimal.ZERO;
        for(OrderCargo orderCargoItem : orderCargos){
            orderPcs += orderCargoItem.getPcs();
            orderWeight = orderWeight.add(orderCargoItem.getWeight());
            if(orderCargoItem.getVolume() != null){
                orderVolume = orderVolume.add(orderCargoItem.getVolume());
            }
        }
        orderParam.setPcs(orderPcs);
        orderParam.setWeight(orderWeight);
        orderParam.setVolume(orderVolume);

        //保存订单生命周期
        OrderLifecycle orderLifecycle = OrderLifecycle.builder()
                .orderNo(orderNo)
                .modifyValue(JSONUtil.toJsonStr(order))
                .operateItem("创建订单")
                .contentDesc("手工新建订单")
                .build();

        this.orderLifecycleService.orderOperateRecord(orderLifecycle,user);
        //保存订单数据
        return this.save(orderParam);
    }

    /**
     * 校验订单号是否已经存在
     * @param orderNo
     */
    private void validateOrderNo(String orderNo){
        QueryWrapper<Order> orderQuery = new QueryWrapper<>();
        orderQuery.lambda().eq(Order::getOrderNo,orderNo);
        //单号已经存在
        Asserts.fail(this.count(orderQuery) > 0,BizMessageEnum.BIZ0000010);
    }

    
    /**
     * 更新订单
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrder(OrderVO order) throws Exception {
        UserInfoVO user = RedisUserService.currentUser();
        //设置订单所在公司和部门,数据隔离
        order.setCompanyId(user.getCompanyId());
        order.setDeptId(user.getDeptId());
        //复制订单中得地址属性
        OrderLocation orderLocation = BeanUtil.copyProperties(order,OrderLocation.class);
        if(order.getLoadingLocationId() != null){
            //校验起运地地址是否存在
            Location loadingLocation = this.locationMapper.selectById(order.getLoadingLocationId());
            Asserts.fail(loadingLocation == null,BizMessageEnum.LOADING_LOCATION_NOT_EXIST);

            orderLocation.setLoadingLocationName(loadingLocation.getLocationName());
            orderLocation.setLoadingProvince(loadingLocation.getProvince());
            orderLocation.setLoadingCity(loadingLocation.getCity());
            orderLocation.setLoadingDistrict(loadingLocation.getDistrict());
            orderLocation.setLoadingLongitude(loadingLocation.getLongitude());
            orderLocation.setLoadingLatitude(loadingLocation.getLatitude());
        }
        if(order.getDischargeLocationId() != null){
            //校验目的地地址是否存在
            Location dischargeLocation = this.locationMapper.selectById(order.getDischargeLocationId());
            Asserts.fail(dischargeLocation == null,BizMessageEnum.DEST_LOCATION_NOT_EXIST);

            orderLocation.setDischargeLocationName(dischargeLocation.getLocationName());
            orderLocation.setDischargeProvince(dischargeLocation.getProvince());
            orderLocation.setDischargeCity(dischargeLocation.getCity());
            orderLocation.setDischargeDistrict(dischargeLocation.getDistrict());
            orderLocation.setDischargeLongitude(dischargeLocation.getLongitude());
            orderLocation.setDischargeLatitude(dischargeLocation.getLatitude());
        }
        //保存订单得地址数据
        orderLocation.setUpdateBy(user.getId());
        orderLocation.setUpdateTime(LocalDateTime.now());
        QueryWrapper<OrderLocation> orderLocationQuery = new QueryWrapper<>();
        orderLocationQuery.lambda().eq(OrderLocation::getOrderNo,order.getOrderNo());
        this.orderLocationMapper.update(orderLocation,orderLocationQuery); //根据订单号修改订单地址
        //更改订单货物数据
        List<OrderCargo> orderCargos = order.getOrderCargos();
        if(CollectionUtils.isEmpty(orderCargos)){
            throw new BizException("货物数据不能为空!");
        }
        //考虑删除货物，修改货物，新增货物
        this.orderCargoService.adjustOrderCargo(orderCargos,order.getOrderNo());
        //统计修改后订单的件毛体
        int orderPcs = 0;
        BigDecimal orderWeight = BigDecimal.ZERO;
        BigDecimal orderVolume = BigDecimal.ZERO;
        for(OrderCargo orderCargoItem : orderCargos){
            orderPcs += orderCargoItem.getPcs();
            orderWeight = orderWeight.add(orderCargoItem.getWeight());
            if(orderCargoItem.getVolume() != null){
                orderVolume = orderVolume.add(orderCargoItem.getVolume());
            }
        }
        order.setPcs(orderPcs);
        order.setWeight(orderWeight);
        order.setVolume(orderVolume);
        //修改订单
        return this.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean checkOrder(OrderVO order) throws Exception {
        if(CollectionUtils.isEmpty(order.getIds()) || order.getOrderStatus() == null){
            throw new BizException("非法请求");
        }
        UserInfoVO user = RedisUserService.currentUser();
        LocalDateTime now = LocalDateTime.now();
        //查询需要审核的订单
        QueryWrapper<Order> orderQuery = new QueryWrapper<>();
        orderQuery.lambda().in(Order::getId,order.getIds())
                .select(Order::getId,Order::getOrderNo,Order::getOrderStatus);
        List<Order> orders = this.list(orderQuery);
        if(CollectionUtils.isEmpty(orders)){
            throw new BizException("待审核的订单不存在");
        }
        if(NumberContants.NUMBER_2 == order.getOrderStatus()){
            //只有正常状态的订单可以审核
            List<Order> otherOrders = orders.stream().filter(item -> NumberContants.NUMBER_1 != item.getOrderStatus()).toList();

            Asserts.fail(CollectionUtils.isNotEmpty(otherOrders),BizMessageEnum.NOT_CHECKED);
        }
        if(NumberContants.NUMBER_1 == order.getOrderStatus()){
            //只有已审核的订单可以反审核
            List<Order> otherOrders = orders.stream().filter(item -> NumberContants.NUMBER_2 != item.getOrderStatus()).toList();
            if(CollectionUtils.isNotEmpty(otherOrders)){
                throw new BizException("只有已审核状态的订单可以反审核");
            }
        }
        //审核或者反审核订单
        UpdateWrapper<Order> orderUpdateWrapper = new UpdateWrapper<>();
        orderUpdateWrapper.lambda().in(Order::getId,order.getIds())
                .set(Order::getOrderStatus,order.getOrderStatus());
        this.update(orderUpdateWrapper);
        //增加订单的生命周期
        List<OrderLifecycle> orderLifecycles = new ArrayList<>();
        for(Order orderItem : orders){
            //保存订单生命周期
            OrderLifecycle orderLifecycle = OrderLifecycle.builder()
                    .orderNo(orderItem.getOrderNo())
                    .modifyValue(order.getOrderStatus().toString())
                    .operateItem("订单审核")
                    .contentDesc(NumberContants.NUMBER_2 == order.getOrderStatus() ? "审核订单": "反审核订单")
                    .build();
            orderLifecycles.add(orderLifecycle);
        }
        this.orderLifecycleService.orderOperateRecord(orderLifecycles,user);
        return true;
    }

    /**
     * 删除订单
     *
     * @param ids 订单ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrders(String ids) {
        Asserts.fail(StrUtil.isBlank(ids),BizMessageEnum.PARAM_IS_NULL);

        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean activeOrLogout(OrderVO order) {
        //激活或者注销业务数据
        Asserts.fail(CollectionUtil.isEmpty(order.getIds()) || order.getOrderStatus() == null,BizMessageEnum.PARAM_IS_NULL);

        List<Order>  orderList = new ArrayList<>(order.getIds().size());
        order.getIds().forEach(id -> {
            Order orderParam = new Order();
            orderParam.setId(id);
            orderParam.setOrderStatus(order.getOrderStatus());
            orderList.add(orderParam);
        });
        this.updateBatchById(orderList,10);
        return true;
    }

}
